package cn.li.org.controller;

import cn.li.basic.util.AjaxResult;
import cn.li.basic.util.PageList;
import cn.li.org.domain.Employee;
import cn.li.org.query.EmployeeQuery;
import cn.li.org.servcie.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 员工管理接口
 *  要求前后端传递参数必须使用json对象
 *  写接口的三要素：
 *    1.请求地址是什么
 *    2.请求参数是什么
 *    3.返回值是什么
 */
@RestController// = @Controller + @ResponseBody
@RequestMapping("/employee")// http://localhost:8080/dept
//@GetMapping =@RequestMapping(value = "/id",method = RequestMethod.GET)
//@PostMapping
//@PutMapping
//@PatchMapping  批量
@Api(value = "员工的API",description="员工相关的CRUD功能")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    //新增和修改   put
    @PutMapping// http://localhost:8080/dept/2
    @ApiOperation(value = "新增或修改，如果传递ID=修改，否则新增" )
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if(employee.getId() == null){
                employeeService.add(employee);
            }else{
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("系统报错了，正在修复中！！");
        }
    }

    // 删除      delete
    @DeleteMapping("/{id}")// http://localhost:8080/dept/2
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            employeeService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("系统报错，正在修復中！！");
        }
    }

    /**
     * 批量删除
     *  前端传递的是数组，后面可以使用List 或者数组接收
     *
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batch(@RequestBody List<Long> ids){
        try {
            employeeService.batch(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("系统报错了，正在修复中！！");
        }
    }


    //获取一条记录  get  /1
    @GetMapping("/{id}")// http://localhost:8080/dept/2
    public Employee queryById(@PathVariable("id") Long id){
        return employeeService.queryById(id);
    }

    //获取所有数据  get
    @GetMapping// http://localhost:8080/dept
    public List<Employee> queryAll(){
        return employeeService.queryAll();
    }

    //分页 + 高级查询  post
    @PostMapping// http://localhost:8080/dept
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery query){
        return employeeService.queryPage(query);
    }

}
